# core/database.py
from sqlalchemy import create_engine, Column, Integer, String, Float, DateTime, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime

Base = declarative_base()

class DownloadTask(Base):
    __tablename__ = "download_tasks"
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    url = Column(String(512), nullable=False)
    status = Column(String(32), default="pending")  # pending/running/paused/completed/failed
    progress = Column(Float, default=0.0)
    speed = Column(String(32), default="0KB/s")
    size = Column(String(32), default="0MB")
    created_time = Column(DateTime, default=datetime.now)
    updated_time = Column(DateTime, default=datetime.now, onupdate=datetime.now)
    name = Column(String(256))
    dir = Column(String(512), default="/downloads")
    format = Column(String(32), default="mp4")
    quality = Column(String(32), default="high")
    download_mode = Column(String(32), default="multithread")  # multithread/ffmpeg
    proxy = Column(String(256))
    headers = Column(Text)
    completed = Column(Integer, default=0)
    total = Column(Integer, default=0)
    message = Column(Text)
    
    def to_sse_dict(self):
        return {
            "id": self.id,
            "status": self.status,
            "progress": self.progress,
            "speed": self.speed,
            "size": self.size,
            "message": self.message,
            "completed": self.completed,
            "total": self.total
        }

# 初始化数据库
engine = create_engine("sqlite:////app/data/downloads.db?check_same_thread=False")
Base.metadata.create_all(bind=engine)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)